<template>
  <div>
    <div class="insp-task-addPage">
      <h3>新建养护任务</h3>
      <div class="insp-task-list">
        <div class="insp-task-topBtn">
          <!-- <el-button size="small" type="primary" @click="handleJumpRecords">
            养护记录
          </el-button>  -->
          <el-select filterable multiple v-model="bridgeId" placeholder="请选择养护桥梁" size="small" style="width: 180px; margin-right: 5px" @change="handleChangeBridge" clearable collapse-tags>
            <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.name" :value="`${item.id};${item.name};${item.lat};${item.lng}`"> </el-option>
          </el-select>
          <el-input placeholder="请输入病害名称" v-model="historyName" size="small" style="width: 180px; margin-right: 5px" clearable> </el-input>
          <el-select v-model="historyStatus" placeholder="请选择处理状态" size="small" style="width: 140px; margin-right: 5px" clearable disabled>
            <el-option v-for="item in historyStatusOpts" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <el-input placeholder="请输入病害部位" v-model="posArr" size="small" style="width: 180px; margin-right: 5px" clearable> </el-input>
          <el-date-picker
            v-model="datetimerange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            :default-time="['12:00:00']"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="margin-right: 5px"
          >
          </el-date-picker>
          <el-button type="primary" size="small" @click="queryHistoryProblems(1)"> 查询 </el-button>
        </div>

        <el-table
          ref="multipleTable"
          :data="tableDeaseData"
          stripe
          :header-cell-style="{
            background: '#8595B9',
            color: '#fff',
            height: '44px',
          }"
          max-height="400px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="_bridgeName" label="桥梁名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="_deasePosition" label="病害位置" show-overflow-tooltip></el-table-column>
          <el-table-column prop="_deaseName" label="病害名称" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="_deaseLevel" label="病害等级" show-overflow-tooltip></el-table-column>
          <el-table-column property="_deaseImage" label="病害图片">
            <template slot-scope="scope">
              <el-image style="width: 60px; height: 60px; margin-top: 10px" :src="scope.row._deaseImage"></el-image>
            </template>
          </el-table-column>
        </el-table>

        <div class="insp-page">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="currentPage"
            :hide-on-single-page="false"
            @current-change="handlePageChange"
            :page-size="pageSize"
            :total="recordsTotal"
          >
          </el-pagination>
        </div>
      </div>

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm insp-task-form">
        <div class="insp-task-addPage-basic">
          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="养护名称 :" prop="name">
                <el-input placeholder="请输入养护名称" v-model="ruleForm.name" size="small" style="width: 70%" clearable> </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="养护类型 :" prop="type">
                <el-select v-model="ruleForm.type" placeholder="请选择养护类型" size="small" style="width: 70%" clearable>
                  <el-option label="日常养护" :value="0"></el-option>
                  <el-option label="亮化养护" :value="1"></el-option>
                  <el-option label="定期养护" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="病害程度 :" prop="diseaseDegree">
                <el-select v-model="ruleForm.diseaseDegree" placeholder="请选择病害程度" size="small" style="width: 70%" clearable>
                  <el-option label="一级" :value="0"></el-option>
                  <el-option label="二级" :value="1"></el-option>
                  <el-option label="三级" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="分发人员:" prop="distributionPersonId">
                <el-select filterable v-model="ruleForm.distributionPersonId" placeholder="请选择分发人员" size="small" style="width: 70%" :filter-method="filterMethod" clearable>
                  <el-option v-for="item in personOptions" :key="item.id" :label="item.name" :value="`${item.id};${item.name}`"> </el-option>
                  <div style="text-align: center">
                    <el-pagination
                      @current-change="handlePageChange_sel"
                      :current-page.sync="currentPage_sel"
                      :hide-on-single-page="true"
                      :page-size="pagesize_sel"
                      layout="prev, pager, next"
                      :total="recordsTotal_sel"
                    >
                    </el-pagination>
                  </div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="养护规则 :" prop="maintenanceNorm">
                <el-select v-model="ruleForm.maintenanceNorm" placeholder="请选择养护规则" size="small" style="width: 70%" clearable>
                  <el-option label="城市规范" :value="0"></el-option>
                  <el-option label="道路规范" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="上级人员 :" prop="reportPerson">
                <el-cascader
                  filterable
                  v-model="ruleForm.companyId"
                  placeholder="请选择上级部门"
                  size="small"
                  :props="prop"
                  style="width: 33%; margin-right: 4%"
                  @change="handleChangeCompany"
                  clearable
                  :options="companyOptions"
                  ref="cascaderAddr"
                >
                </el-cascader>
                <el-select filterable v-model="ruleForm.leaderId" placeholder="请选择上级人员" size="small" style="width: 33%" clearable>
                  <el-option v-for="item in leaderOptions" :key="item.id" :label="item.name" :value="`${item.id};${item.name}`"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务时间 :" prop="taskTime">
                <el-date-picker
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['12:00:00']"
                  style="width: 70%"
                  v-model="ruleForm.taskTime"
                  type="datetimerange"
                  size="small"
                  range-separator="——"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  clearable
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务紧急度 :" prop="taskDegree">
                <el-select v-model="ruleForm.taskDegree" placeholder="请选择任务紧急度" size="small" style="width: 70%" clearable>
                  <el-option label="一般" :value="0"></el-option>
                  <el-option label="中度" :value="1"></el-option>
                  <el-option label="紧急" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="24">
              <el-form-item label="养护描述 :" prop="maintenanceDescribe">
                <el-input type="textarea" maxlength="200" rows="4" v-model="ruleForm.maintenanceDescribe" style="width: 90%" show-word-limit> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div style="text-align: center; margin-top: 10px; margin-bottom: 20px">
        <el-button type="default" size="small" class="cancel" @click="handleCancel">取消</el-button>
        <el-button type="primary" class="submit" size="small" @click="handleSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import base from '@/api/base'
export default {
  props: {},
  data() {
    var validateReportPerson = (rule, value, callback) => {
      if (!this.ruleForm.companyId) {
        callback(new Error('请选择上级部门'))
      } else if (!this.ruleForm.leaderId) {
        callback(new Error('请选择上级人员'))
      } else {
        callback()
      }
    }
    return {
      prop: {
        value: 'id',
        label: 'name',
      },
      id: '', //this.$route.query.id
      currentPage_sel: 1,
      recordsTotal_sel: 0,
      pagesize_sel: 10,

      pageSize: 4,
      currentPage: 1,
      recordsTotal: 0,

      historyName: '',
      historyStatus: 0,
      historyStatusOpts: [
        {
          label: '待养护',
          value: 0,
        },
        {
          label: '养护中',
          value: 1,
        },
        {
          label: '已处理',
          value: 2,
        },
      ],

      datetimerange: [],
      posArr: '',

      personOptions: [],
      companyOptions: [],
      leaderOptions: [],
      bridgeOptions: [],
      tableDeaseData: [],
      multipleSelection: [],
      bridgeId: [],
      ruleForm: {
        name: '',
        type: '',
        diseaseDegree: '',
        distributionPersonId: '',
        maintenanceNorm: '',
        taskTime: '',
        maintenanceDescribe: '',
        companyId: [],
        leaderId: '',
        taskDegree: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入养护名称',
            trigger: 'blur',
          },
        ],
        type: [
          {
            required: true,
            message: '请选择养护类型',
            trigger: 'change',
          },
        ],
        diseaseDegree: [
          {
            required: true,
            message: '请选择病害程度',
            trigger: 'change',
          },
        ],
        distributionPersonId: [
          {
            required: true,
            message: '请选择分发人员',
            trigger: 'change',
          },
        ],
        maintenanceNorm: [
          {
            required: true,
            message: '请选择养护规则',
            trigger: 'change',
          },
        ],
        reportPerson: [
          {
            required: true,
            validator: validateReportPerson,
            trigger: 'change',
          },
        ],
        taskTime: [
          {
            required: true,
            message: '请选择任务时间',
            trigger: 'change',
          },
        ],
        taskDegree: [
          {
            required: true,
            message: '请选择任务紧急度',
            trigger: 'change',
          },
        ],
      },
      deaseDialogVisible: false,
    }
  },
  created() {
    this.queryPersonOpts(1)
    this.queryCompanyOpts()
    this.queryBridgeOpts()
    this.queryHistoryProblems(1)
  },
  watch: {
    $route() {
      this.emptyForm()
      this.historyName = ''
      this.datetimerange = []
      this.posArr = ''
      this.bridgeId = []

      this.queryPersonOpts(1)
      this.queryCompanyOpts()
      this.queryBridgeOpts()
      this.queryHistoryProblems(1)
    },
  },
  methods: {
    emptyForm() {
      this.$refs['ruleForm'].resetFields()
      const emptyObj = {
        name: '',
        type: '',
        diseaseDegree: '',
        distributionPersonId: '',
        maintenanceNorm: '',
        taskTime: '',
        maintenanceDescribe: '',
        companyId: [],
        leaderId: '',
        taskDegree: '',
      }
      this.ruleForm = emptyObj
    },
    queryBridgeOpts() {
      this.$api.bridge.AllTheBridges().then((response) => {
        if (response.data.success) {
          this.bridgeOptions = response.data.data[0]
        }
      })
    },
    handleChangeBridge(val) {
      this.bridgeId = val
    },
    queryPersonOpts(pageIndex, name) {
      if (pageIndex && pageIndex === 1) {
        this.currentPage_sel = 1
      }
      let _params = {
        pageSize: this.pagesize_sel,
        pageNum: this.currentPage_sel,
        type: 1,
      }
      if (name) {
        _params['name'] = name
      }
      this.$api.curing.queryPersonPage(_params).then((response) => {
        if (response.data.success) {
          this.personOptions = response.data.data
          this.recordsTotal_sel = response.data.recordsTotal
        }
      })
    },
    handlePageChange_sel(currentPage) {
      this.currentPage_sel = currentPage
      this.queryPersonOpts()
    },
    filterMethod(name) {
      this.queryPersonOpts(1, name)
    },
    handleChangeCompany(val) {
      if (val[val.length - 1])
        this.queryCompanyPersonsOpts({
          id: val[val.length - 1],
        })
    },
    queryCompanyOpts() {
      this.$api.curing.queryCompanyList().then((response) => {
        if (response.data.success) {
          this.companyOptions = response.data.data
        }
      })
    },
    queryCompanyPersonsOpts(params) {
      this.$api.curing.queryCompanyPersonsList(params).then((response) => {
        if (response.data.success) {
          this.leaderOptions = response.data.data.personMap
          if (!response.data.data.personMap.length)
            this.$vs.notify({
              text: '暂无人员',
              color: 'danger',
            })
        }
      })
    },
    handleSubmit() {
      //console.log(this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels);
      this.$refs.ruleForm.validate(async (valid, model) => {
        if (!valid) {
          return false
        }
        if (this.multipleSelection.length <= 0) {
          this.$vs.notify({
            text: '请添加病害',
            color: 'danger',
          })
          return false
        }

        let _userInfo = JSON.parse(localStorage.getItem('userInfo'))
        let _params = {
          createUserId: _userInfo['userid'] || '',
          createUserName: _userInfo['realname'] || '',
          name: this.ruleForm.name,
          type: this.ruleForm.type,
          diseaseDegree: this.ruleForm.diseaseDegree,
          maintenanceNorm: this.ruleForm.maintenanceNorm,
          maintenanceDescribe: this.ruleForm.maintenanceDescribe,
          distributionPersonId: this.ruleForm.distributionPersonId.split(';')[0],
          distributionPersonName: this.ruleForm.distributionPersonId.split(';')[1],
          reportPersonId: this.ruleForm.leaderId.split(';')[0],
          reportPersonName: this.ruleForm.leaderId.split(';')[1],
          reportDept: this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels.join('/'),
          bridgeId: this.multipleSelection.map((item) => item['ownId']).join(','),
          bridgeName: this.multipleSelection.map((item) => item['ownName']).join(','),
          startTime: this.ruleForm.taskTime[0],
          endTime: this.ruleForm.taskTime[1],
          lat: this.multipleSelection.map((item) => (item['ext8'] ? item['ext8'].split(',')[1] : '')).join(','),
          lng: this.multipleSelection.map((item) => (item['ext8'] ? item['ext8'].split(',')[0] : '')).join(','),
          inspIds: this.multipleSelection.map((item) => item.id).join(','),
          urgencyLevel: this.ruleForm.taskDegree,
        }
        if (this.editId) {
          _params.id = this.editId
        }

        this.$api.curing.addCuringTask(_params).then((response) => {
          if (response.data.success) {
            this.$vs.notify({
              text: '新增成功',
              color: 'success',
            })
            this.$router.push('/curing/task')
          }
        })
      })
    },
    handleCancel() {
      this.$router.push('/curing/task')
    },
    handleJumpRecords() {
      this.$router.push('/curing/record')
    },
    handleDeleteItem(item, index) {
      this.multipleSelection.splice(index, 1)
    },
    queryHistoryProblems(pageIndex) {
      let _userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (pageIndex && pageIndex === 1) {
        this.currentPage = 1
      }
      let _params = {
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        data: {
          name: this.historyName,
          status: this.historyStatus,
          ownIds: this.bridgeId.map((item) => item.split(';')[0]).join(','),
          location: this.posArr,
          endTime: this.datetimerange.length > 1 ? this.datetimerange[1] : '',
          startTime: this.datetimerange.length > 1 ? this.datetimerange[0] : '',
          diseaseFlag: 1,
          userId: _userInfo['userid'] || '',
        },
      }
      this.$api.insp.queryHistoryPage(_params).then((response) => {
        if (response.data.success) {
          this.tableDeaseData = response.data.data.map((item, index) => {
            const _deasePosition = item.ext3 ? JSON.parse(item.ext3)['deasePosition'] : []
            return {
              ...item,
              _bridgeName: item.ownName || '',
              _deaseName: item.ext6 || '',
              _deaseLevel: item.ext3 ? this.levelText(JSON.parse(item.ext3)['level']) : '',
              _deasePosition: _deasePosition.length > 0 ? _deasePosition[0].split(';')[1] : '',
              _deaseImage: item.ext1 ? `${base.DOWNLOADURL}${item.ext1.split(';').length > 0 ? item.ext1.split(';')[0] : ''}` : '',
            }
          })
          this.recordsTotal = response.data.recordsTotal
        }
      })
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage
      this.queryHistoryProblems()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    levelText(val) {
      switch (val) {
        case 0:
          return '一级'
        case 1:
          return '二级'
        case 2:
          return '三级'
      }
    },
    judgeDiseaseLocation(val) {
      switch (val) {
        case '桥面系':
          return '0'
        case '上部结构':
          return '1'
        case '下部结构':
          return '2'
        case '其他':
          return '3'
      }
    },
  },
}
</script>
<style scoped lang="scss">
@import '@/views/inspection/insp.scss';

/deep/.el-table__header tr,
/deep/.el-table__header th {
  padding: 0;
  height: 44px;
}

/deep/.el-table td,
/deep/.el-table th {
  text-align: center;
  font-size: 14px;
}

/deep/.el-table th {
  font-weight: 500;
  color: #fff;
}

/deep/.el-table td {
  font-weight: 400;
  color: #444;
  padding: 0;
  height: 44px;
  line-height: 44px;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f1f5fc;
}

// /deep/.el-button--mini.insp-task-addBtn {
//   padding: 6px;
//   font-size: 18px;
//   font-weight: bolder;
// }

.cancel,
.submit {
  padding: 5px 28px !important;
  border-radius: 0;
  font-size: 16px !important;
  font-weight: normal;
  line-height: 22px;
  margin-top: 30px;
}

.cancel {
  background: rgba(255, 255, 255, 1);
  color: rgba(184, 190, 202, 1);
  margin-right: 50px;
}

.submit {
  background: $mainColor;
  color: #fff;
}
</style>
